﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CNotebook;
using CNotebook.Inventory;

namespace NotebookS2
{
    public partial class WHTransferRecvd: DevExpress.XtraBars.Ribbon.RibbonForm
    {
        public WHTransferRecvd()
        {
            InitializeComponent();
        }
        
        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }
        public DataTable LineItems { get; set; }

        #region Function

        bool IsComplete()
        {
            RemoveBlankLastRowFirst();

            foreach (DataRow oRow in this.LineItems.Rows)
            {
                if (Convert.ToDouble(oRow["RcvdQty"]) <= 0)
                {
                    return false;
                }
            }

            return true;
        }
        void RemoveBlankLastRowFirst()
        {
            
            string sItemCode = "";


            sItemCode = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ItemCode"]).ToString();

            if (sItemCode.Trim() == "")
            {
                gridView1.DeleteRow(gridView1.FocusedRowHandle);
            }
        }

        public void PrintPreview()
        {
            PRNT_WTS oPrint = new PRNT_WTS();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocumentNumber.Text;

            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }

        public void OpenDocument(string sDocumentNumber)
        {
            BindWarehouse();

            BindWarehouseAndExclude(cboSource.SelectedValue.ToString());

          
            WTManager oManager = new WTManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataRow oRow = oManager.GetWarehouseTransfer(sDocumentNumber);


            #region Header
            txtDocumentNumber.Text = oRow["DocNum"].ToString();
            txtStatus.Text = oRow["DocStatus"].ToString();

            dtPostDate.Value = Convert.ToDateTime(oRow["PostingDate"]);
            cboSource.SelectedValue = oRow["SourceWhCode"].ToString();
            cboDestination.SelectedValue = oRow["DestWhCode"].ToString();

            txtRemarks.Text = oRow["Remarks"].ToString();
            txtDriver.Text = oRow["Driver"].ToString();
            txtHelper.Text = oRow["Helper"].ToString();

            txtDateCreated.Text = oRow["DateCreated"].ToString();
            txtCreatedBy.Text = oRow["CreatedBy"].ToString();
            txtDateModified.Text = oRow["DateModified"].ToString();
            txtModifiedBy.Text = oRow["ModifiedBy"].ToString();


            #endregion

            #region Line Items
            this.LineItems = oManager.GetLineItems(sDocumentNumber);
            gridControl1.DataSource = this.LineItems;
            gridControl1.Refresh();
            #endregion

            oManager.Close();

            if (txtStatus.Text == "In-Transit")
            {
                btnAdd.Text = "Received";
            }
            else
            {
                btnAdd.Text = "Update";
                btnAdd.Enabled = false;
            }
        }

     
        DataTable GetLineTable()
        {
            DataTable _table = new DataTable();

            _table.Columns.Add("ItemCode", typeof(string));
            _table.Columns.Add("Bar_Code", typeof(string));
            _table.Columns.Add("ItemName", typeof(string));
            _table.Columns.Add("Qty", typeof(double));
            _table.Columns.Add("RcvdQty", typeof(double));
            _table.Columns.Add("UoM", typeof(string));
            _table.Columns.Add("LotNumber", typeof(string));
            _table.Columns.Add("ExpiryDate", typeof(string));
            _table.Columns.Add("MfrDate", typeof(string));

            return _table;
        }

        void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();


            cboSource.DataSource = oManager.GetWarehouse();
            cboSource.DisplayMember = "Dscription";
            cboSource.ValueMember = "Code";

            cboSource.Refresh();


            oManager.Close();
        }

        void BindWarehouseAndExclude(string _ExcludeWarehouse)
        {
            WarehouseManager oManager = new WarehouseManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();


            cboDestination.DataSource = oManager.GetWarehouseAndExclude(_ExcludeWarehouse);
            cboDestination.DisplayMember = "Dscription";
            cboDestination.ValueMember = "Code";

            cboDestination.Refresh();


            oManager.Close();
        }

        void DisableControls()
        {
            dtPostDate.Enabled = false;
            cboSource.Enabled = false;
            cboDestination.Enabled = false;
            txtDocumentNumber.Properties.ReadOnly = true;
            txtRemarks.Properties.ReadOnly = true;
            txtDriver.Properties.ReadOnly = true;
            txtHelper.Properties.ReadOnly = true;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oCol in gridView1.Columns)
            {
                if (txtStatus.Text == "In-Transit" && oCol.Name == "RcvdQty")
                {
                    oCol.OptionsColumn.AllowEdit = true;
                }
                else
                {
                    oCol.OptionsColumn.AllowEdit = false;
                }
            }
        }

        void EnableControls()
        {
            dtPostDate.Enabled = true;
            cboSource.Enabled = true;
            cboDestination.Enabled = true;
            
            txtRemarks.Properties.ReadOnly = false;
            txtDriver.Properties.ReadOnly = false;
            txtHelper.Properties.ReadOnly = false;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oCol in gridView1.Columns)
            {
                if (oCol.Name == "Dscription" || oCol.Name == "UoM" || oCol.Name == "LotNumber" || oCol.Name == "ExpiryDate" || oCol.Name == "ColMfrDate")
                {
                    oCol.OptionsColumn.AllowEdit = false;
                }
                else
                {
                    oCol.OptionsColumn.AllowEdit = true;
                }
            }
        }


        #endregion

        public int ObjectType { get { return 103; } }

        string ApplyAuthorization()
        {
            UserManager oManager = new UserManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            string iAccessType = oManager.GetAccessType(this.ObjectType, this.ActiveUserID);

            oManager.Close();

            switch (iAccessType)
            {
                case "Full Access":
                    FullAccess();
                    break;
                case "Read Only":
                    ApplyReadOnly();
                    break;
                case "No Access":
                    NoAccess();
                    break;
            }

            return iAccessType;
        }


        int ApplyReadOnly()
        {
            DisableControls();

            txtStatus.Properties.Buttons[0].Enabled = false;
            txtStatus.Properties.Buttons[1].Enabled = false;


            return 2;
        }

        int FullAccess()
        {
            txtStatus.Properties.Buttons[0].Enabled = true;
            txtStatus.Properties.Buttons[1].Enabled = true;

            return 1;
        }

        int NoAccess()
        {
            MessageBox.Show("You have no right to access this module!!!!", "Security Policy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 3;

        }



        private void WHTransferOut_Load(object sender, EventArgs e)
        {
            
        }

        private void cboSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                dtPostDate.Value = System.DateTime.Now;
                BindWarehouseAndExclude(cboSource.SelectedValue.ToString());
                
            }
            catch
            {
            }
        }

        private void ribbonControl1_Click(object sender, EventArgs e)
        {

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }



        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtStatus.Text == "In-Transit")
            {
                WTManager oManager = new WTManager();

                if (MessageBox.Show("Are you sure you to set to Received?", "WTS", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                        if (gridView1.RowCount >= 1)
                        {
                            RemoveBlankLastRowFirst();
                        }

                        WTUnit oUnit = new WTUnit();
                        oUnit.DocumentNumber = txtDocumentNumber.Text;
                        oUnit.PostingDate = dtPostDate.Value;
                        oUnit.SourceWarehouse = cboSource.SelectedValue.ToString();
                        oUnit.DestinationWarehouse = cboDestination.SelectedValue.ToString();
                        oUnit.Remarks = txtRemarks.Text;
                        oUnit.Driver = txtDriver.Text;
                        oUnit.Helper = txtHelper.Text;

                        oUnit.DocumentStatus = txtStatus.Text;
                        oUnit.DateCreated = Convert.ToDateTime(txtDateCreated.Text);
                        oUnit.CreatedBy = txtCreatedBy.Text;
                        oUnit.DateModified = Convert.ToDateTime(txtDateCreated.Text);
                        oUnit.ModifiedBy = txtModifiedBy.Text;

                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();
                        this.LineItems = oManager.GetLineItems(oUnit.DocumentNumber);
                        oUnit.LineItems = this.LineItems;



                        

                        System.Data.SqlClient.SqlException ex = oManager.UpdateTransfer(oUnit);
                        oManager.Close();

                        oUnit.LineItems.AcceptChanges();

                        if (ex == null)
                        {
                            oManager = new WTManager();

                            oManager.ConnectionString = this.ConnectionString;
                            oManager.Open();

                            oManager.ChangeToReceived(cboDestination.SelectedValue.ToString(), txtDocumentNumber.Text);
                            txtStatus.Text = "Received";
                            oManager.Close();
                            return;
                        }
                        else
                        {
                            MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    

                }
                
            }


        }

        private void btnSearchItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_ITM_WH oForm = new FND_ITM_WH();

            oForm.SourceWarehouse = cboSource.SelectedValue.ToString();
            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            int iRowHandle = gridView1.FocusedRowHandle;

            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["ItemCode"], oForm.Code);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["Bar_Code"], oForm.BarCode);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["ItemName"], oForm.Description);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["UoM"], oForm.UOM);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["LotNumber"], oForm.LotNumber);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["ExpiryDate"], oForm.ExpiryDate);
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];

                if (e.KeyCode == Keys.Delete)
                {
                    if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        gridView1.DeleteRow(iCount);
                    }
                }

                if (e.KeyCode == Keys.Down)
                {
                    if (gridView1.IsLastRow)
                    {
                        string sItemCode = "";
                        oRow = gridView1.GetSelectedRows();

                        iCount = oRow[0];
                        sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                        if (sItemCode != "")
                        {
                            gridView1.AddNewRow();
                        }
                    }
                }
            }
            catch
            {
            }
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "In-Transit")
            {
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = false;

            }
            
            if (txtStatus.Text == "Received" || txtStatus.Text == "Canceled")
            {
                btnAdd.Enabled = false;
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
            }
        }

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtStatus.Text == "Draft")
            {
                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                {
                    if (MessageBox.Show("Are you sure you to set to Transit-Mode?", "WTS", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        WTManager oManager = new WTManager();

                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();

                        oManager.ChangeToTransitMode(cboSource.SelectedValue.ToString(), txtDocumentNumber.Text);
                        txtStatus.Text = "In-Transit";
                        oManager.Close();
                        return;
                    }
                }

                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                {
                    if (MessageBox.Show("Are you sure you want to cancel the document?", "WTS", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        WTManager oManager = new WTManager();

                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();

                        oManager.CancelDocument(txtDocumentNumber.Text);
                        txtStatus.Text = "Canceled";
                        oManager.Close();
                        return;
                    }
                }
            }


            if (txtStatus.Text == "In-Transit")
            {
                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                {
                    if (MessageBox.Show("Are you sure you to set to Received?", "WTS", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        bool HasZeroValue = false;

                        foreach (DataRow oRow in this.LineItems.Rows)
                        {
                            if (oRow["RcvdQty"] == DBNull.Value)
                            {
                                HasZeroValue = true;
                                break;
                            }
                        }

                        if (HasZeroValue == false)
                        {
                            WTManager oManager = new WTManager();

                            oManager.ConnectionString = this.ConnectionString;
                            oManager.Open();

                            oManager.ChangeToReceived(cboDestination.SelectedValue.ToString(), txtDocumentNumber.Text);
                            txtStatus.Text = "Received";
                            oManager.Close();
                        }
                        else
                        {
                            MessageBox.Show("Please insert received quantity!!!", "Received", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        return;
                    }
                }
            }
        }

        private void txtRcvdQty_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.CalcEdit _RECEIVED_QTY = (DevExpress.XtraEditors.CalcEdit)sender;

            double dReceivedQty = 0;

            try
            {
                dReceivedQty = Convert.ToDouble(_RECEIVED_QTY.EditValue);
            }
            catch
            {
                dReceivedQty = 0;
            }

            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["RcvdQty"], dReceivedQty.ToString());

        }
    }
}
